package com.linkage.seapeak.activity.message;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.CreateProTalkActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.ShowMultiDataActivity;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.seapeak.adapter.MsgMemberAdapter;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.pojo.CrediterNewUser;
import com.linkage.seapeak.pojo.CrediterUser;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 群发消息第一步，选择人员
 */
public class ZQMultiSelectActivity extends BaseWhiteActivity implements AYSwipeRecyclerView.OnRefreshLoadListener {

    List<CrediterNewUser> userList;
    AYSwipeRecyclerView recyclerView;
    MsgMemberAdapter adapter;

    TextView  all_select, screen_member;
    TextView menu;

    String projectId;

    static Boolean committee;
    static  Boolean onlineStatus;
    static Boolean kindTax;
    static Boolean kindGuarantee;
    static Boolean kindOther;
    static Boolean kindOrdinary;
    static Double minAmountDeclared;
    static Double maxAmountDeclared;
    static Double minConfirmAmount;
    static Double maxConfirmAmount;
    static String processStatus;

    int pageNo = 1;
    int pageSize = 20;
    String type = "0";

    //选择人员列表
    List<CrediterNewUser> selectList;
    List<CrediterNewUser> noselectList;
    //已选择人的ids;
    boolean allflag = true;

    List<String> selectIds;
    List<String> noselectIds;
    List<String> alreadySelectIds;
    boolean canSelectAlready = true;

    String form = "";

    boolean isAll = false;

    /**
     * 开启页面
     * @param context
     * @param projectId
     */
    public static void start(Context context, String projectId,Boolean i_committee,Boolean i_online,Boolean i_kindTax,
                             Boolean i_kindGuarantee,Boolean i_kindOther,Boolean i_kindOrdinary,Double i_minAmountDeclared,
                             Double i_maxAmountDeclared,Double i_minConfirmAmount,Double i_maxConfirmAmount,String i_processStatus){
        Intent intent = new Intent(context, ZQMultiSelectActivity.class);
        intent.putExtra("projectId", projectId);

        committee = i_committee;

        onlineStatus = i_online;
        kindTax = i_kindTax;
        kindGuarantee = i_kindGuarantee;
        kindOther = i_kindOther;
        kindOrdinary = i_kindOrdinary;
        minAmountDeclared = i_minAmountDeclared;
        maxAmountDeclared = i_maxAmountDeclared;
        minConfirmAmount =i_minConfirmAmount;
        maxConfirmAmount = i_maxConfirmAmount;
        processStatus = i_processStatus;


        context.startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.SHOWFINISH)) {
            finish();
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multi_select_zq, "选择成员");
        init();
        EventBus.getDefault().register(this);
        loadFirst();
    }

    private void init() {
        projectId = getIntent().getStringExtra("projectId");
        canSelectAlready = getIntent().getBooleanExtra("canSelectAlready", true);
        alreadySelectIds = getIntent().getStringArrayListExtra("alreadySelectIds");
        if (alreadySelectIds == null)
            alreadySelectIds = new ArrayList<>();
        selectIds = new ArrayList<>();
        noselectIds = new ArrayList<>();
        selectIds.addAll(alreadySelectIds);

        try {
            type = getIntent().getStringExtra("type");
            form =  getIntent().getStringExtra("form");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (type == null)
            type = "0";

        recyclerView = findViewById(R.id.member_list);
        all_select = findViewById(R.id.all_select);
        screen_member = findViewById(R.id.screen_member);

        userList = new ArrayList<>();
        selectList = new ArrayList<>();
        noselectList= new ArrayList<>();
        recyclerView.setOnRefreshLoadLister(this);
        recyclerView.setMode(AYSwipeRecyclerView.SwipeType.ONLY_START);
        adapter = new MsgMemberAdapter(ZQMultiSelectActivity.this, userList, true);
        recyclerView.setAdapter(adapter);
        recyclerView.startLoadFirst();
        recyclerView.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position, RecyclerView.ViewHolder viewHolder) {
                if (!canSelectAlready && alreadySelectIds.contains(userList.get(position).getCreditorid()))
                    return;

                boolean itemCheck = userList.get(position).isCheck;
                userList.get(position).isCheck = !itemCheck;
                if (!itemCheck) {
                    selectList.add(userList.get(position));
                    selectIds.add(userList.get(position).getCreditorid());

                    for(int i = 0;i < noselectList.size();i++) {
                        if (noselectList.get(i).getSysUserId().equals(userList.get(position).getSysUserId())) {
                            noselectList.remove(userList.get(position));
                            noselectIds.remove(userList.get(position).getCreditorid());
                            break;
                        }
                    }

                } else {
                    for(int i = 0;i < selectList.size();i++) {
                        if (selectList.get(i).getSysUserId().equals(userList.get(position).getSysUserId())) {
                            selectList.remove(userList.get(position));
                            selectIds.remove(userList.get(position).getCreditorid());
                            break;
                        }
                    }
                    noselectList.add(userList.get(position));
                    noselectIds.add(userList.get(position).getCreditorid());
                }
                adapter.notifyDataSetChanged();
                if ("0".equalsIgnoreCase(type)) {
                    menu.setText("下一步(" + selectList.size() + ")");
                } else {
                    menu.setText("完成(" + selectList.size() + ")");
                }
            }
        });

        all_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isAll = !isAll;
                all_select.setText(isAll ? "取消" : "全选");
                adapter.setAllSelect(isAll);
                selectList.clear();
                if (isAll)
                    selectList.addAll(userList);
                if ("0".equalsIgnoreCase(type)) {
                    menu.setText("下一步(" + selectList.size() + ")");
                } else {
                    menu.setText("完成(" + selectList.size() + ")");
                }
                adapter.notifyDataSetChanged();
            }
        });

        screen_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(ZQMultiSelectActivity.this, ZQScreenUserActivity.class), 0x11);
            }
        });

        menu = (TextView) addMenu(new MenuAction(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectList == null || selectList.size() == 0) {
                    showToast("请至少选择一个成员");
                    return;
                }

                String noselectIdlist = "";
                for(int i=0;i<noselectIds.size();i++)
                {

                    noselectIdlist += noselectIds.get(i)+",";
                }
                ShowMultiDataActivity.start(ZQMultiSelectActivity.this,projectId,committee,onlineStatus,kindTax,
                        kindGuarantee,kindOther,kindOrdinary,minAmountDeclared,
                        maxAmountDeclared,  minConfirmAmount,maxConfirmAmount,processStatus,noselectIdlist,"");

//                Intent data=new Intent(Intent.ACTION_SENDTO);
//                data.setData(Uri.parse("mailto:8692801@qq.com"));
//                data.putExtra(Intent.EXTRA_SUBJECT, "这是标题");
//                data.putExtra(Intent.EXTRA_TEXT, "这是内容");
//                startActivity(data);
////
//                if ("1".equalsIgnoreCase(type)) {
//                    String seluserName = "";
//                    String seluserId = "";
//
//                    for (int i = 0; i < selectList.size(); i++) {
//                        CrediterUser user = selectList.get(i);
//                        if (user != null) {
//                            seluserName = seluserName + user.getCreditorname() + ",";
//                            if("sysuserid".equalsIgnoreCase(form)) {
//                                seluserId = seluserId + user.getSysUserId() + ",";
//                            }else{
//                                seluserId = seluserId + user.getId() + ",";
//                            }
//                        }
//                    }
//                    Intent intent = new Intent(ZQMultiSelectActivity.this, CreateProTalkActivity.class);
//                    intent.putExtra("seluserName", seluserName);
//                    intent.putExtra("seluserId", seluserId);
//                    setResult(RESULT_OK, intent);
//                    finish();
//                    return;
//                } else if ("2".equalsIgnoreCase(type)){
//                    Intent intent = new Intent();
//                    intent.putExtra("userList", (Serializable) selectList);
//                    setResult(RESULT_OK, intent);
//                    finish();
//                } else {
//                    Intent intent = new Intent(ZQMultiSelectActivity.this, MultiSendActivity.class);
//                    intent.putExtra("projectId", projectId);
//                    intent.putExtra("userList", (Serializable) selectList);
//                    startActivity(intent);
//                    finish();
//                }



            }
        }, "下一步", 0));
        if ("0".equalsIgnoreCase(type)) {
            menu.setText("下一步");
        } else {
            menu.setText("完成");
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在界面销毁的地方要解绑
        EventBus.getDefault().unregister(this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x11 && resultCode == RESULT_OK && data != null) {

        }
    }

    @Override
    public void loadFirst() {
        pageNo = 1;
//        if (type.equals("2"))
            getCreditorList(true);
//        else
//            creditorListCnd(true);
    }

    @Override
    public void loadNext() {
//        if (type.equals("2"))
            getCreditorList(false);
//        else
//            creditorListCnd(false);
    }

    /**
     * 获取成员
     */
//    public void creditorListCnd(final boolean isFirst) {
//        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
//            getToken(null);
//            return;
//        }
//        Map<String, String> parms = new HashMap<>();
//        parms.put("userToken", getUserToken());
//        parms.put("projectId", projectId);
//        parms.put("pageNumber", pageNo + "");
//        parms.put("pageSize", pageSize + "");
//        if (committee != null) parms.put("committee", committee + "");
//        if (onlineStatus != null) parms.put("onlineStatus", onlineStatus + "");
//        if (kindTax != null) parms.put("kindTax", kindTax + "");
//        if (kindGuarantee != null) parms.put("kindGuarantee", kindGuarantee + "");
//        if (kindOther != null) parms.put("kindOther", kindOther + "");
//        if (kindOrdinary != null) parms.put("kindOrdinary", kindOrdinary + "");
//        if (minAmountDeclared != null && minAmountDeclared != 0f) parms.put("minAmountDeclared", minAmountDeclared + "");
//        if (maxAmountDeclared != null && maxAmountDeclared != 0f) parms.put("maxAmountDeclared", maxAmountDeclared + "");
//        if (minConfirmAmount != null && minConfirmAmount != 0f) parms.put("minConfirmAmount", minConfirmAmount + "");
//        if (maxConfirmAmount != null && maxConfirmAmount != 0f) parms.put("maxConfirmAmount", maxConfirmAmount + "");
//        if (processStatus != null) parms.put("processStatus", processStatus + "");
//
//        Network.getAPIService()
//                .creditorListCnd(parms)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new BaseSubscriber<JsonObject>() {
//                    @Override
//                    public void onNext(JsonObject json) {
//                        int code = json.get("code").getAsInt();
//                        if (code != 0) {
//                            showToast(json.get("msg").getAsString());
//                            recyclerView.onFinishRequest(true, false);
//                        } else {
//                            if (isFirst) {
//                                userList.clear();
//                                selectList.clear();
//                            }
//
//                            JsonObject data = json.getAsJsonObject("data");
//                            JsonObject jsonpagination = data.getAsJsonObject("pagination");
//                            JsonArray array = jsonpagination.getAsJsonArray("list");
//                            List<CrediterUser> temp = new ArrayList<>();
//                            for (int i = 0;i < array.size();i++) {
//                                CrediterUser item = new Gson().fromJson(array.get(i), CrediterUser.class);
//                                if (selectIds.contains(item.getCreditorid())) {
//                                    item.isCheck = true;
//                                    selectList.add(item);
//                                } else
//                                    item.isCheck = false;
//                                temp.add(item);
//                            }
//
//                            userList.addAll(temp);
//                            int count = data.get("totalCount").getAsInt();
//                            recyclerView.onFinishRequest(false, pageNo * pageSize < count);
//                            pageNo++;
//                        }
//                    }
//
//                    @Override
//                    public void onCompleted() {
//                        super.onCompleted();
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        recyclerView.onFinishRequest(true, false);
//                    }
//                });
//    }

    /**
     * 获取成员
     */
    public void getCreditorList(final boolean isFirst) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }


                Map<String, String> parms = new HashMap<>();
        parms.put("userToken", getUserToken());
        parms.put("projectId", projectId);
        parms.put("pageNumber", pageNo + "");
        parms.put("pageSize", pageSize + "");
        parms.put("committee", committee + "");
        if (onlineStatus != null) parms.put("onlineStatus", onlineStatus + "");
        if (kindTax ) parms.put("kindTax", kindTax + "");
        if (kindGuarantee ) parms.put("kindGuarantee", kindGuarantee + "");
        if (kindOther ) parms.put("kindOther", kindOther + "");
        if (kindOrdinary   ) parms.put("kindOrdinary", kindOrdinary + "");
        if (minAmountDeclared != null && minAmountDeclared != 0f) parms.put("minAmountDeclared", minAmountDeclared + "");
        if (maxAmountDeclared != null && maxAmountDeclared != 0f) parms.put("maxAmountDeclared", maxAmountDeclared + "");
        if (minConfirmAmount != null && minConfirmAmount != 0f) parms.put("minConfirmAmount", minConfirmAmount + "");
        if (maxConfirmAmount != null && maxConfirmAmount != 0f) parms.put("maxConfirmAmount", maxConfirmAmount + "");
        if (processStatus != null) parms.put("processStatus", processStatus + "");

        Network.getAPIService()
                .getCreditorListNew(parms)
//                .getCreditorList(getUserToken(), projectId, committee, onlineStatus,
//                        kindTax, kindGuarantee, kindOther, kindOrdinary, minAmountDeclared,
//                        maxAmountDeclared, minConfirmAmount, maxConfirmAmount, processStatus,
//                        orderBy, orderColumn, pageNo, pageSize)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onError(new Throwable(json.get("msg").getAsString()));
                            return;
                        } else {
                            if (isFirst) {
                                userList.clear();
                                selectList.clear();
                            }



                            JsonObject data = json.getAsJsonObject("data");
                            JsonObject pagination = data.getAsJsonObject("pagination");

                            JsonArray array = pagination.getAsJsonArray("list");
                            List<CrediterNewUser> temp = new ArrayList<>();

                            if(array.size()==0)
                            {
                                menu.setVisibility(View.INVISIBLE);
                                all_select.setVisibility(View.INVISIBLE);
                            }else{
                                menu.setVisibility(View.VISIBLE);
                                all_select.setVisibility(View.VISIBLE);

                            }
                            for (int i = 0;i < array.size();i++) {
                                CrediterNewUser item = new Gson().fromJson(array.get(i), CrediterNewUser.class);
                                if (selectIds.contains(item.getCreditorid())) {
                                    item.isCheck = true;
                                    if (isAll)
                                        selectList.add(item);
                                } else
                                    item.isCheck = false;
                                temp.add(item);
                            }

                            userList.addAll(temp);

                            try {
                                int count = data.get("totalCount").getAsInt();
                                recyclerView.onFinishRequest(false, pageNo * pageSize < count);
                            }catch (Exception ex)
                            {
                                recyclerView.onFinishRequest(false, true);
                                ex.printStackTrace();
                            }
                            pageNo++;
                            if(isFirst) {
                                isAll = true;
                                all_select.setText(isAll ? "取消" : "全选");
                                adapter.setAllSelect(isAll);
                                selectIds.clear();
                                if (isAll) {
                                    for (CrediterNewUser idStr : userList) {
                                        selectIds.add(idStr.getId());
                                    }
                                }
                                menu.setText("完成(" + selectIds.size() + ")");

                            }
                            adapter.setAllSelect(isAll);
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        recyclerView.onFinishRequest(true, false);
                    }
                });
    }
}
